package com.qf.cardlike.service.impl;



import com.google.common.base.Joiner;
import com.qf.cardlike.domain.User;
import com.qf.cardlike.mapper.UserMapper;
import com.qf.cardlike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(String username, String password) {
        List<User> users = userMapper.selectByName(username);
        for (User user:users) {
            if (Objects.equals(password,user.getPassword())){
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
        //喜欢哪个名片 不喜欢 【删除】哪个名片
        User user = userMapper.selectByPrimaryKey(Long.valueOf(userId));
        //喜欢的那些名字
        String likefIds = user.getLiked();
        if (like){
            //喜欢哪个名片 liked追加名片id
            likefIds = StringUtils.isEmpty(likefIds)? cardId.toString() : likefIds+","+cardId;

        }else {
            // 如果不喜欢哪个名片
            // 说明：Arrays.asList() 方法返回的List对象是一个Arrays的内部类，这个内部类不支持集合的添加add()/移除remove()操作
            List<String> likedIDList = Arrays.stream(likefIds.split(",")).collect(Collectors.toList());
            likedIDList.remove(cardId.toString());
            // 把这个集合转换为逗号分割的字串 google提供了一个工具guava这个工具
            likefIds = Joiner.on(",").join(likedIDList);
        }
        user.setLiked(likefIds);
        userMapper.updateByPrimaryKeySelective(user);
        return user;
    }
}
